import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import '../../../../model/mediaItem.dart';
import 'dart:typed_data';

class PhotoGrid extends StatefulWidget {
  final List<AssetEntity> photos;
  final List<AssetEntity> videos;
  final List<MediaItem>? mediaItems;
  final VoidCallback onAddMore;
  final Function(int) onRemove;

  const PhotoGrid({
    Key? key,
    required this.photos,
    required this.videos,
    required this.onAddMore,
    required this.onRemove,
    this.mediaItems,
  }) : super(key: key);

  @override
  State<PhotoGrid> createState() => _PhotoGridState();
}

class _PhotoGridState extends State<PhotoGrid>
    with AutomaticKeepAliveClientMixin {
  // 缓存Future而不是数据，避免FutureBuilder重建
  static final Map<String, Future<Uint8List?>> _thumbnailCache = {};

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context); // 必须调用，用于 AutomaticKeepAliveClientMixin

    List<dynamic> allMedia = widget.mediaItems != null
        ? widget.mediaItems!
        : [...widget.photos, ...widget.videos];

    return Container(
      height: 72,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: allMedia.length + 1,
        itemBuilder: (context, index) {
          if (index == allMedia.length) {
            return RepaintBoundary(child: _buildAddButton());
          }

          if (allMedia[index] is MediaItem) {
            return RepaintBoundary(
              child: _buildMediaItemFromMediaItem(
                  allMedia[index] as MediaItem, index),
            );
          } else {
            return RepaintBoundary(
              child: _buildMediaItem(allMedia[index] as AssetEntity, index),
            );
          }
        },
      ),
    );
  }

  Widget _buildAddButton() {
    return Container(
      width: 60,
      height: 60,
      padding: EdgeInsets.only(top: 12),
      child: GestureDetector(
        onTap: widget.onAddMore,
        child: Container(
          width: 60,
          height: 60,
          decoration: BoxDecoration(
            color: const Color(0xFF222222),
            borderRadius: BorderRadius.circular(4),
          ),
          child: Icon(Icons.add, color: Colors.white, size: 24),
        ),
      ),
    );
  }

  Widget _buildMediaItem(AssetEntity media, int index) {
    return Container(
      width: 72,
      height: 72,
      padding: EdgeInsets.only(right: 12, top: 12),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 缩略图 - 使用缓存的Future
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              color: Colors.grey[300],
            ),
            child: FutureBuilder<Uint8List?>(
              future: _getCachedThumbnail(media), // 使用缓存的Future
              builder: (context, snapshot) {
                if (snapshot.hasData && snapshot.data != null) {
                  return ClipRRect(
                    borderRadius: BorderRadius.circular(4),
                    child: Image.memory(
                      snapshot.data!,
                      fit: BoxFit.cover,
                      width: 60,
                      height: 60,
                      gaplessPlayback: true,
                    ),
                  );
                }
                return Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                    color: Colors.grey[300],
                  ),
                  child: Center(
                    child: CircularProgressIndicator(
                      strokeWidth: 2,
                      valueColor:
                          AlwaysStoppedAnimation<Color>(Colors.grey[600]!),
                    ),
                  ),
                );
              },
            ),
          ),
          // 视频播放图标
          if (media.type == AssetType.video)
            Positioned.fill(
              child: Center(
                child: Container(
                  width: 24,
                  height: 24,
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(Icons.play_arrow, color: Colors.white, size: 16),
                ),
              ),
            ),
          // 关闭按钮
          Positioned(
            top: -8,
            right: -8,
            child: GestureDetector(
              onTap: () => widget.onRemove(index),
              child: Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(shape: BoxShape.circle),
                child: Image.asset(
                  'assets/icons/icon_close_rounded.png',
                  width: 24,
                  height: 24,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: Colors.black87,
                        shape: BoxShape.circle,
                      ),
                      child: Icon(Icons.close, color: Colors.white, size: 12),
                    );
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMediaItemFromMediaItem(MediaItem media, int index) {
    return Container(
      width: 72,
      height: 72,
      padding: EdgeInsets.only(right: 12, top: 12),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              color: Colors.grey[300],
            ),
            child: _buildThumbnailFromMediaItem(media),
          ),
          // 视频播放图标
          if (media.type == AssetType.video)
            Positioned.fill(
              child: Center(
                child: Container(
                  width: 24,
                  height: 24,
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    shape: BoxShape.circle,
                  ),
                  child: Icon(Icons.play_arrow, color: Colors.white, size: 16),
                ),
              ),
            ),
          // 关闭按钮
          Positioned(
            top: -8,
            right: -8,
            child: GestureDetector(
              onTap: () => widget.onRemove(index),
              child: Container(
                width: 24,
                height: 24,
                decoration: BoxDecoration(shape: BoxShape.circle),
                child: Image.asset(
                  'assets/icons/icon_close_rounded.png',
                  width: 24,
                  height: 24,
                  errorBuilder: (context, error, stackTrace) {
                    return Container(
                      width: 24,
                      height: 24,
                      decoration: BoxDecoration(
                        color: Colors.black87,
                        shape: BoxShape.circle,
                      ),
                      child: Icon(Icons.close, color: Colors.white, size: 12),
                    );
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildThumbnailFromMediaItem(MediaItem media) {
    if (media.isNetworkImage) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Image.network(
          media.networkUrl!,
          fit: BoxFit.cover,
          width: 60,
          height: 60,
          gaplessPlayback: true, // 减少闪烁
          loadingBuilder: (context, child, loadingProgress) {
            if (loadingProgress == null) return child;
            return Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                color: Colors.grey[300],
              ),
              child: Center(
                child: CircularProgressIndicator(
                  strokeWidth: 2,
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[600]!),
                ),
              ),
            );
          },
          errorBuilder: (context, error, stackTrace) {
            return Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                color: Colors.grey[300],
              ),
              child: Center(
                child: Icon(Icons.error, color: Colors.grey[600]),
              ),
            );
          },
        ),
      );
    } else {
      return FutureBuilder<Uint8List?>(
        future: _getCachedThumbnail(media.assetEntity!), // 使用缓存的Future
        builder: (context, snapshot) {
          if (snapshot.hasData && snapshot.data != null) {
            return ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: Image.memory(
                snapshot.data!,
                fit: BoxFit.cover,
                width: 60,
                height: 60,
                gaplessPlayback: true, // 减少闪烁
              ),
            );
          }
          return Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4),
              color: Colors.grey[300],
            ),
            child: Center(
              child: CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[600]!),
              ),
            ),
          );
        },
      );
    }
  }

  // 关键优化：缓存Future实例而不是数据
  Future<Uint8List?> _getCachedThumbnail(AssetEntity entity) {
    final key = "${entity.id}_${ThumbnailSize(200, 200).toString()}";

    if (_thumbnailCache.containsKey(key)) {
      return _thumbnailCache[key]!; // 返回同一个Future实例
    } else {
      final future = entity.thumbnailDataWithSize(ThumbnailSize(200, 200));
      _thumbnailCache[key] = future; // 缓存Future而不是结果
      return future;
    }
  }
}
